import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

public final class Utils {
    /**
     * 创建指定的目录
     *
     * @param path 要创建的文件夹地址
     */
    public static void createDir(String path) {
        //创建根文件夹
        File folder = new File(path);
        if (!folder.exists() && !folder.isDirectory()) {
            if (folder.mkdirs()) {
                System.out.println("创建文件夹" + path + "成功");
            } else {
                System.out.println("创建文件夹" + path + "失败");
            }
        } else {
            System.out.println(folder + "文件夹已创建");
        }
    }

    /**
     * 下载文件到指定的目录
     * @param dir
     * @param fileUrl
     * @throws IOException
     */
    public static void downloadFile(String dir, String imageName, String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        URLConnection uri = url.openConnection();
        InputStream is = uri.getInputStream();
        OutputStream os = new FileOutputStream(new File(dir, imageName ));
        byte[] buf = new byte[1024];
        int len = -1;
        while ((len = is.read(buf)) != -1) {
            os.write(buf,0 ,len);
        }
    }

    /**
     * GBK转UTF-8
     * https://blog.csdn.net/weixin_43641651/article/details/85265550
     *
     * @param gbkStr GBK字符串
     * @return 返回UTF-8编码的字节数组
     */
    public static byte[] gbk2Utf8_Bytes(String gbkStr) {
        int n = gbkStr.length();
        byte[] utfBytes = new byte[3 * n];
        int k = 0;
        for (int i = 0; i < n; i++) {
            int m = gbkStr.charAt(i);
            if (m < 128) {
                utfBytes[k++] = (byte) m;
                continue;
            }
            utfBytes[k++] = (byte) (0xe0 | (m >> 12));
            utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));
            utfBytes[k++] = (byte) (0x80 | (m & 0x3f));
        }
        if (k < utfBytes.length) {
            byte[] tmp = new byte[k];
            System.arraycopy(utfBytes, 0, tmp, 0, k);
            return tmp;
        }
        return utfBytes;
    }

    /**
     * GBK转UTF-8
     * https://blog.csdn.net/weixin_43641651/article/details/85265550
     *
     * @param gbkStr GBK字符串
     * @return 返回UTF-8编码的字符串
     */
    public static String gbk2Utf8(String gbkStr) {
        return new String(gbk2Utf8_Bytes(gbkStr), StandardCharsets.UTF_8);
    }
}
